package com.wetao.lib_common.greendao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;

import com.wetao.lib_common.greendao.dao.DaoMaster;
import com.wetao.lib_common.greendao.dao.DaoSession;


/**
 * Created by apple on 2017/7/4.
 * 封装Greendao数据库
 */

public class GreenDaoHelper {

    Context context;
    //DaoMaster.DevOpenHelper helper;
    DaoMaster.OpenHelper helper;
    SQLiteDatabase db;
    DaoMaster daoMaster;
    DaoSession daoSession;


    public GreenDaoHelper(Context context) {
        this.context = context;
    }

    public DaoSession initDao(String userId){
        if (!userId.equals(""))
        {
            /**
             * 可以继承自OpenHelper或者DevOpenHelper
             * OpenHelper:创建表，默认升级表是不做任何操作 ---必须选这个
             * DevOpenHelper:创建表，默认升级表示删除所有表，然后新建空的表 --不能选这个，会删除所有表
             * */
            //helper = new DaoMaster.DevOpenHelper(context, "db_" + userId, null);//没有数据库升级
            helper = new SQLiteOpenHelper(context, "db_" + userId);//有数据库升级
            db = helper.getWritableDatabase();
            daoMaster = new DaoMaster(db);
            daoSession = daoMaster.newSession();
            return daoSession;
        }else {
            return null;
        }
    }


    public void close() {
        if(db != null) {
            db.close();
        }
    }
}
